package com.itdl.generater.config;

import cn.hutool.core.lang.generator.SnowflakeGenerator;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 雪花算法全局唯一ID生成器配置
 */
@Configuration
@SuppressWarnings("all")
public class SnowflakeIdGeneratorUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    /**
     * 创建SnowflakeGenerator，用于生成唯一的ID
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(SnowflakeGenerator.class)
    public SnowflakeGenerator snowflakeGenerator(){
        return new SnowflakeGenerator();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SnowflakeIdGeneratorUtil.applicationContext = applicationContext;
    }


    /**
     * 获取唯一的全局ID
     * @return 雪花算法生成的唯一ID
     */
    public static Long getUniqueId(){
        return applicationContext.getBean(SnowflakeGenerator.class).next();
    }
}
